package com.itheima.wemedia.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author danzhiheng
 * @version 1.1
 * @date 2023/2/6 17:48
 */
@Service
@Slf4j
public class ApiServiceImpl implements ApiService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private com.itheima.admin.feign.AdChannelFeign adChannelFeign;

    /**
     * 调用后台微服务，获取频道列表。
     * 优先使用redis缓存
     *
     * @return
     */
    @Override
    public List<AdChannel> getChannelList() {
        List<AdChannel> channelList = new ArrayList<>();
        //4.1 优先从redis中查询记录
        String key = SystemConstants.REDISKEY_CHANNELLIST;
        String channelJsonList = stringRedisTemplate.opsForValue().get(key);
        //4.2 如果redis没命中，则远程调用admin微服查询所有的频道列表
        if (StrUtil.isEmpty(channelJsonList)){
            //远程调用admin微服查询所有的频道列表
            ResultVo<List<AdChannel>> listResult = adChannelFeign.listAll();
            if (!listResult.isSuccess()){
                log.error("远程调用admin微服查询频道列表失败! {}", listResult.getErrorMessage());
                throw new LeadNewsException("查询数据失败，请稍后重试!");
            }
            channelList = listResult.getData();
            //   如果没有频道
            if (CollectionUtil.isEmpty(channelList)){
                // 则  存入redis，值为空的list，长度为0，设置有效时长为5s
                channelList = new ArrayList<>();
                stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(channelList),5, TimeUnit.SECONDS);
            }else {
                // 有数据，则把数据存入redis中，不设置有效时长
                stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(channelList));
            }
        }else {
            // 若redis命中，转化为java List对象
            channelList = JSON.parseArray(channelJsonList,AdChannel.class);
        }
        return channelList;
    }
}
